<?php
            
use app\model\Theme; 
use app\model\Poster; 



class Index_Page extends PluginMobilePage {
    /**
     * Desc:渲染页面
     * User: mf
     * Time: 2023/10/25 10:00
     */
    function main(){
        global $_P,$_G,$_S,$_C;
        $system = $_S;
        $themeid = $_P['themeid'];
        $fromtype = $_P['from'];
        if ($fromtype=='mobile') {
            $fans = $this->checkuser();
            $uid = $fans['uid'];
        }
        if ($fromtype=='wxapp') {
            $uid = $_P['uid'];
        }
        $config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME_TABEL,'themeid'=>$themeid));
        $help_gift=$tuan_gift=$invite_gift = [];
        if($config['open_tuan_gift']==1&&!empty($config['tuan_gift'])){
            $tuan_gift = GiftModel::format($config['tuan_gift'],'tuan_gift');
        }
        if($config['open_invite_gift']==1&&!empty($config['invite_gift'])){
            $invite_gift = GiftModel::format($config['invite_gift'], 'invite_gift');
        }
        if($config['open_help_gift']==1&&!empty($config['help_gift'])){
            $help_gift = GiftModel::format($config['help_gift'], 'help_gift');
        }
        $merge_gift_array = array_merge($help_gift,$tuan_gift,$invite_gift);
        if(empty($merge_gift_array)){
            return_json(201,'未配置');
        }
        $theme = Theme::getThemeById($themeid);
        //限制时间范围
        $time = date("Y-m-d H:i:s",time());
        //小于开始时间不显示
        if($config['is_limit_time']==1){
            if($time<$config['limit_start_time']){
                return_json(201,'时间未到');
            }
        }else{
            if(time()<$theme['begintime']){
                return_json(201,'时间未到');
            }
        }
        //判断身份 -1未登录，或没订单；0团长；1团员；
        if(empty($uid)){
            $identity = -1;
            return_json(201,'未登录');
        }else{
            $record = db_find("SELECT * FROM ".tablename(t_record)." WHERE  themeid='$themeid' AND uid='$uid' AND (status=1 OR status=3 OR status=-2) order by  id desc");
            if(empty($record)){
                $identity = -1;
            }else{
                $identity = $record['type'];
            }
        }
        $gift_array=[];
        foreach ($merge_gift_array as $key => $value){
            $l_gift_recordall = db_getall(t_intive_gift_record,array('themeid'=>$themeid,'uid'=>$uid,'classify'=>$value['classify'],'taskid'=>$value['taskid']));
            $count_gift_recordall = count($l_gift_recordall);
            if($count_gift_recordall>0){
                for ($i=0; $i<$count_gift_recordall; $i++){
                    $value['gift_recordid'] = $l_gift_recordall[$i]['id'];
                    $value['gift_record'] = $l_gift_recordall[$i];
                    $gift_array[]=$value;
                }
            }else{
                $gift_array[]=$value;
            }
        }
        //小程序
        if ($fromtype=='wxapp') {
            $list = [];
            $online_list = [];
        }
        if ($fromtype=='mobile') {
            $style_mode = $config['style_mode'];
            $welfarelist_li = '';
            $unclaimed = [];
        }
        $worker = db_get(t_worker,array('uid'=>$uid));
        foreach ($gift_array as $key1 => $value1){
            $gift_record = $value1['gift_record'];
            //未中奖 根据配置礼品来
            if(empty($gift_record)){
                $gift = db_get(t_intive_gift,array('id'=>$value1['gift_id'],'themeid'=>$themeid),array('name','top_img','price','remark'));
            }else{
                //中奖的 根据中奖记录显示礼品
                $gift = db_get(t_intive_gift,array('id'=>$gift_record['gift_id'],'themeid'=>$themeid),array('name','top_img','price','remark'));
            }
            //限制身份
            //当前是团长
            if($identity==0&&empty($gift_record)){
                //不能展示关于团员的
                if($value1['identity']==3){
                    continue;
                }
            }
            //当前是团员
            if($identity==1&&empty($gift_record)){
                //不能展示关于团长的
                if($value1['identity']==1){
                    continue;
                }
            }
            //限制时间范围
            if($config['is_limit_time']==1){
                //大于结束时间仅显示，未核销和已核销的礼品
                if($time> $config['limit_end_time']){
                    if($gift_record['status']==0||empty($gift_record)){
                        continue;
                    }
                }
            }else{
                //大于结束时间仅显示，未核销和已核销的礼品
                if(time()>$theme['endtime']){
                    if($gift_record['status']==0||empty($gift_record)){
                        continue;
                    }
                }
            }

            //上下架限制 下架后已获得的奖品依然显示
            if($value1['status']==2&&empty($gift_record)){
                continue;
            }
            if(!empty($worker)){
                $classify_text = '员工不可参与';
                $gift_record['status'] = -1;
                if($fromtype=='mobile'){
                    $gift_record_style = '';
                    $gift_record_p = '';
                }
                $status_txt = '我要解锁';
            }else {
                //成团礼文字组合
                if ($value1['classify'] == 'tuan_gift') {
                    //配置项身份：团长
                    if ($value1['identity'] == 1) {
                        //当前没订单
                        if ($identity == -1) {
                            $classify_text = '成为团长，团满' . $value1["number"] . '人可解锁';
                        } else {
                            if (!empty($gift_record)) {
                                $classify_text = '您是团长，团满' . $value1["number"] . '人，已解锁';
                            } else {
                                $recordall = db_select("SELECT id,uid FROM " . tablename(t_record) . " WHERE  themeid='$themeid'  AND pid='" . $record['pid'] . "'   AND (status=1 OR status=3 OR status=-2) ");
                                $number = $value1["number"] - count($recordall);
                                $classify_text = '再邀请' . $number . '人参团可解锁  ';
                            }
                        }
                    }
                    //配置项身份:团长+团员
                    if ($value1['identity'] == 2) {
                        //当前用户没身份
                        if ($identity == -1) {
                            $classify_text = '参团后，团满' . $value1["number"] . '人可解锁';
                        } else {
                            if (!empty($gift_record)) {
                                $classify_text = '团满' . $value1["number"] . '人，已解锁';
                            } else {
                                $recordall = db_select("SELECT id,uid FROM " . tablename(t_record) . " WHERE  themeid='$themeid'  AND pid='" . $record['pid'] . "'   AND (status=1 OR status=3 OR status=-2) ");
                                $number = $value1["number"] - count($recordall);
                                $classify_text = '再邀请' . $number . '人参团可解锁';
                            }
                        }
                    }
                    //配置项身份：团员
                    if ($value1['identity'] == 3) {
                        //当前没订单
                        if ($identity == -1) {
                            $classify_text = '成为团员，团满' . $value1["number"] . '人可解锁';
                        } else {
                            if (!empty($gift_record)) {
                                $classify_text = '您是团员，团满' . $value1["number"] . '人，已解锁';
                            } else {
                                $recordall = db_select("SELECT id,uid FROM " . tablename(t_record) . " WHERE  themeid='$themeid'  AND pid='" . $record['pid'] . "'   AND (status=1 OR status=3 OR status=-2) ");
                                $number = $value1["number"] - count($recordall);
                                $classify_text = '再邀请' . $number . '人参团可解锁  ';
                            }
                        }
                    }
                }
                //邀请礼文字组合
                if ($value1['classify'] == 'invite_gift') {
                    //查询当前人邀请了多少人下单，被邀请人所有订单只统计一次
                    $recordall = GiftModel::recordCount($themeid,$uid);
                    $number = $value1["number"] - $recordall;
                    //配置项身份:不限制
                    if ($value1['identity'] == 0) {
                        //当前用户没身份
                        if (!empty($gift_record)) {
                            $classify_text = '您邀请了' . $value1["number"] . '位好友报名，已解锁';
                        } else {
                            $classify_text = '再邀请' . $number . '位好友报名可解锁';
                        }
                    }
                    //配置项身份：团长
                    if ($value1['identity'] == 1) {
                        //当前用户没身份
                        if ($identity == -1) {
                            $classify_text = '成为团长后，邀请' . $value1["number"] . '人报名可解锁';
                        } else {
                            if (!empty($gift_record)) {
                                $classify_text = '您是团长，邀请了' . $value1["number"] . '人，已解锁';
                            } else {
                                $classify_text = '您是团长，再邀请' . $number . '位好友报名可解锁';
                            }
                        }
                    }
                    //配置项身份：团员
                    if ($value1['identity'] == 3) {
                        //当前用户没身份
                        if ($identity == -1) {
                            $classify_text = '报名参团后，邀请' . $value1["number"] . '人报名可解锁';
                        } else {
                            if (!empty($gift_record)) {
                                $classify_text = '您邀请了' . $value1["number"] . '位好友报名,已解锁';
                            } else {
                                $classify_text = '再邀请' . $number . '位好友报名，可解锁';
                            }
                        }
                    }
                    //配置项身份：仅限支付客户
                    if ($value1['identity'] == 4) {
                        //当前用户没身份
                        if ($identity == -1) {
                            $classify_text = '您报名后，再邀请' . $value1["number"] . '人报名可解锁';
                        } else {
                            if (!empty($gift_record)) {
                                $classify_text = '您邀请了' . $value1["number"] . '人已解锁';
                            } else {
                                $classify_text = '再邀请' . $number . '位好友报名，可解锁';
                            }
                        }
                    }
                }
                //助力礼文字组合
                if ($value1['classify'] == 'help_gift') {
                    if (!empty($gift_record)) {
                        $classify_text = '您邀请了' . $value1["number"] . '位好友助力，已解锁';
                    } else {
                        $friendall = db_getall(t_friend, array('themeid' => $themeid, 'fromuid' => $uid), array('id'));
                        $number = $value1["number"] - count($friendall);
                        $classify_text = '再邀请' . $number . '位好友助力可解锁';
                    }
                }
                //状态文字
                if (!empty($gift_record)) {
                    if ($fromtype == 'mobile') {
                        $gift_record_style = 'geted';
                        $gift_record_p = 'used';
                    }
                    $status_txt = GiftModel::statusList($gift_record['status'], $gift_record['type']);
                } else {
                    $gift_record['status'] = -1;
                    if ($fromtype == 'mobile') {
                        $gift_record_style = '';
                        $gift_record_p = '';
                    }
                    $status_txt = GiftModel::statusList($gift_record['status']);
                }
            }
            //小程序页面数据
            if ($fromtype=='wxapp') {
                $list[$key1]['classify_text'] =  $classify_text;
                $list[$key1]['gift_recordid'] =  $gift_record['id'];
                $list[$key1]['status'] =  $gift_record['status'];
                $list[$key1]['freeze'] =  $gift_record['freeze'];
                $list[$key1]['pid'] =  $gift_record['pid'];
                $list[$key1]['status_txt'] =  $status_txt;
                $list[$key1]['gift_top_img'] =  $gift['top_img'];
                $list[$key1]['gift_name'] =  $gift['name'];
                $list[$key1]['gift_price'] =  $gift['price'];
                $list[$key1]['remark'] =  $value1['remark'];
            }
            //h5页面数据
            if ($fromtype=='mobile') {
                //备注显示
                $span_style = "";
                if(empty($value1['remark'])){
                    $span_style = "style='border: 1px solid #ffffff;'";
                }
                //列表样式
                if ($style_mode == 1) {
                    $welfarelist_li .= '<li>
                                    <div class="welfareImg">
                                        <img src="' . $gift["top_img"] . '" alt="">
                                    </div>
                                     <div class="welfareTxt">
                                        <div class="right_div right_div2">
                                            <h2>' . $gift["name"] . '</h2>
                                            <a href="javascript:void(0);" 
                                                class="welfareState welfareState2 ' . $gift_record_style . '"  
                                                data-gift_recordid="' . $gift_record["id"] . '"  
                                                data-status="' . $gift_record["status"] . '" 
                                                data-freeze="' . $gift_record["freeze"] . '" 
                                                data-number="' . $value1["number"] . '"
                                                data-classify="' . $value1["classify"] . '"
                                                onclick="receive(this)" >
                                                &nbsp;' . $status_txt . '
                                            </a>
                                        </div>';
                    if ($gift["price"] && $gift["price"]>0){
                        $welfarelist_li.= '<p>价值&nbsp;<i>¥<b>' . $gift["price"] . '</b></i></p>';
                    }
                    $welfarelist_li .='<span ' . $span_style . '>' . $value1["remark"] . '</span><p class="p2 '.$gift_record_p.' pp2" style="margin-top: .1rem;">' . $classify_text . '</p></div></li>';
                }
                if ($style_mode == 2) {
                    $welfarelist_li .= '<li>
                                        <div class="welfareImg">
                                            <img src="' . $gift["top_img"] . '" alt="">
                                        </div>
                                        <div class="welfareTxt">
                                            <h2>' . $gift["name"] . '</h2>
                                            <span ' . $span_style . '>' . $value1["remark"] . '</span>
                                            <div class="right_div">';
                    if ($gift["price"] && $gift["price"]>0){
                        $welfarelist_li .= '<p>价值&nbsp;<i>¥<b>' . $gift["price"] . '</b></i></p>';
                    }
                    $welfarelist_li .= '<a href="javascript:void(0);" 
                                                    class="welfareState ' . $gift_record_style . '" 
                                                    data-gift_recordid="' . $gift_record["id"] . '" 
                                                    data-status="' . $gift_record["status"] . '"  
                                                    data-freeze="' . $gift_record["freeze"] . '"  
                                                    data-number="' . $value1["number"] . '"  
                                                    data-classify="' . $value1["classify"] . '"  
                                                    onclick="receive(this)">
                                                    ' . $status_txt . '
                                                </a>
                                            </div>
                                            <p class="p2 '.$gift_record_p.' ">' . $classify_text . '可解锁</p>
                                        </div>
                                    </li>';
                }
            }
            //拥有礼品弹窗
            if ($gift_record['display_num'] == -1) {
                $ii++;
                if ($fromtype=='mobile') {
                    if ($config['exchange_mode'] == 1) {
                        $prompt = '<p>实物礼品仅可选择一个兑换</p>';
                    }else{
                        $prompt = '';
                    }
                    $unclaimed_html = '
                            <h2>
                                恭喜获得礼品
                                <span class="closeOnlie" onclick="unclaimed_close()"></span>
                            </h2>
                            <div class="contactEwm">
                                <img src="' . $gift["top_img"] . '" style="pointer-events:auto;" >
                                <div class="gift_name">' . $gift["name"] . '</div>
                                ' . $prompt . '
                            </div>
                            <div class="get_div" >
                                <div class="iknow"  onclick="unclaimed_close()">已知晓</div>
                            </div>
                ';
                    $unclaimed[$ii]['html'] = Theme::encode($unclaimed_html);
                    $unclaimed[$ii]['state'] = -1;
                }
                if ($fromtype=='wxapp') {
                    $online_list[$ii]['top_img'] = $gift["top_img"];
                    $online_list[$ii]['name'] = $gift["name"];
                    $online_list[$ii]['state'] = -1;
                }
                db_update(t_intive_gift_record, ['display_num' => 1], ['id' => $gift_record['id']]);
            }
        }

        if ($fromtype=='mobile') {
            $res['unclaimed'] = $unclaimed;
            $res['html']['welfarelist_li'] = Theme::encode($welfarelist_li);
        }
        if ($fromtype=='wxapp') {
            $res['list'] = $list ;

            $res['online_list'] = $online_list ;
        }

        $res['config']['show_mode'] = $config['show_mode'];
        $res['config']['exchange_mode'] = $config['exchange_mode'];
        $res['config']['style_mode'] = $config['style_mode'];
        $res['config']['buoy_img'] = $config['buoy_img'];
        $res['config']['invite_gift'] = $system['invite_gift'];
        return_json(200,'ok',$res);
    }


    /**
     * Desc:核销页
     * User: mf
     * Time: 2023/11/15 10:38
     */
    function w_verified(){
        global $_P,$_G,$_S,$_C;
        $themeid = $_P['themeid'];
        $fromtype = $_P['from'];
        $gift_recordid = $_P['gift_recordid'];
        $user = $this->checkuser();
        $workerid = $user['uid'];
        $worker = db_get(t_worker,array('uid'=>$workerid));
        $company = $worker['company'];
        if(empty($worker)){
            if($fromtype=='wxapp'){
                return_json(201,'您不是工作人员');
            }
            if ($fromtype=='mobile') {
                return_msg('您不是工作人员');
            }
        }
        $gift_record = db_get(t_intive_gift_record,array('id'=>$gift_recordid),array('uid'));
        $uid = $gift_record['uid'];
        $fans = db_get(t_fans,array('uid'=>$uid));
        $sql = " select r.*,g.name,w.username as workername,w.mobile as workermobile  from ".tablename(t_intive_gift_record)."  as r left join ".tablename(t_intive_gift)." as g   on g.id=r.gift_id  
        left join ".tablename(t_worker)." as w on w.uid=r.workerid  WHERE r.uid='$uid'  and  r.themeid='$themeid' and r.shangjiaid='$company'" ;
        $list = db_select($sql);
        $gift_config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME_TABEL,'themeid'=>$themeid));
        $tuan_gift = GiftModel::format($gift_config['tuan_gift'],'tuan_gift');
        $invite_gift = GiftModel::format($gift_config['invite_gift'],'invite_gift');
        $gift_array = array_merge($tuan_gift,$invite_gift);
        $gift_recordids = '';
        foreach ($list as $index => $item) {
            if($item['status']==1){
                if(empty($gift_recordids)){
                    $gift_recordids .= $item['id'];
                }else{
                    $gift_recordids .= ','.$item['id'];
                }
            }
            foreach ($gift_array as $key => $value){
                if($value['classify']==$item['classify']&&$value['taskid'] == $item['taskid']){
                    if($value['classify']=='tuan_gift'){
                        $list[$index]['tiaojian'] = $value["number"].'人成团';
                    }
                    if($value['classify']=='invite_gift'){
                        $list[$index]['tiaojian'] = '邀请'.$value["number"].'人下单';
                    }
                }
            }
        }
        $res = [];
        $res['list'] = $list;
        $res['fans'] = $fans;
        $res['gift_config'] = $gift_config;
        if($fromtype=='wxapp'){
            return_json(200,'ok',$res);
        }
        if ($fromtype=='mobile') {
            $return_clicent = get_defined_vars();
return $this->view('/gift/index/verified' , $return_clicent);
        }
    }

    function is_verified()
    {
        global $_P,$_G,$_S,$_C;
        $verify_type = $_P['verify_type'];
        $themeid = $_P['themeid'];
        $gift_recordid = $_P['gift_recordid'];
        $gift_record_uid = $_P['gift_record_uid'];
        $fromtype = $_P['from'];
        $user = $this->checkuser();
        $workerid = $user['uid'];
        $worker = db_get(t_worker,array('uid'=>$workerid),array('id'));
        $gift_config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME_TABEL,'themeid'=>$themeid),array('exchange_mode'));
        if($gift_config['exchange_mode']==1){
            $gift_record = db_get(t_intive_gift_record,array('uid'=>$gift_record_uid,'status'=>2),array('id'));
            if(!empty($gift_record)){
                return_json(201,'已核销过一个礼品');
            }
        }
        if(empty($worker)){
            return_json(201,'您不是工作人员');
        }
        $exchange_at = date("Y-m-d H:i:s",time());
        $update = array('status'=>2,'workerid'=>$workerid,'exchange_at'=>$exchange_at);

        if($verify_type == 'only'){
            $result = db_update(t_intive_gift_record,$update, array('id' => $gift_recordid));
        }
        if($verify_type == 'all'){
            if($fromtype=='wxapp'){
                $gift_recordids = $gift_recordid;
            }
            if ($fromtype=='mobile') {
            $gift_recordids = explode(',',$gift_recordid);
            }

            if($gift_config['exchange_mode']==1){
                if(count($gift_recordids)>1){
                    return_json(201,'只能核销一个');
                }
            }
            for ($i=0; $i<count($gift_recordids); $i++){
                $result = db_update(t_intive_gift_record,$update, array('id' => $gift_recordids[$i]));
            }

        }
        if(!empty($result)){
            return_json(200,'核销成功');
        }else{
            return_json(201,'错误');
        }
    }
    /**
     * Desc:核销码
     * User: mf
     * Time: 2023/11/7 08:58
     */
    function qr_code ()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        $themeid = $_P['themeid'];
        $gift_recordid = $_P['gift_recordid'];
        if ($fromtype=='mobile') {
            $fans = $this->checkuser();
            $uid = $fans['uid'];
            $qrcodeurl =  $_G['siteroot'].createMobileUrl('wx',array("themeid"=>$themeid,"from"=>"mobile","r"=>"gift.index.w_verified","gift_recordid"=>$gift_recordid));
            return_json(200,'ok',['qrimg'=>$qrcodeurl]);
        }
        if($fromtype=='wxapp'){
            $theme = Theme::getThemeById($themeid);
            $uid = $_P['uid'];
            $gift_record = db_get(t_intive_gift_record,array('uid'=>$uid),array('id'));
            $gift_recordid = $gift_record['id'];
            $scene = MODULE_NAME . "-" . $theme['id'] . "-" . $uid . "-" . $theme['softkey'] . "-".$gift_recordid ;
            $url = 'Worker/pages/w_gift_verified/w_gift_verified';
            $qrimg = Poster::CreateScene($_S,$scene,$_C,$url);
            $qrimg = str_replace('http:', 'https:', $qrimg);
            return_json(200,'ok',['qrimg'=>$qrimg]);
        }

    }








}
